<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="添加" v-model="visible" align-center width="1300px"
    :z-index="2000" @close="handleClose">
    <div class="flex mb-3">
      <el-button type="primary" @click="add">添加sku</el-button>
      <el-button @click="batchRemove">删除</el-button>
    </div>
    <el-form>
      <div class="flex items-center gap-2">
        <el-form-item label="活动类型">
          <VSelect v-model="form.promotion_config_id" placeholder="请选择" :options="options.typeOptions" select filterable
            clearable class="w-32" />
        </el-form-item>
        <el-form-item label="国家">
          <VSelect v-model="form.country" placeholder="请选择" :options="options.country" select filterable clearable
            class="w-32" @change="form.warehouse_id = ''" />
        </el-form-item>
        <el-form-item label="仓库">
          <VSelect v-model="form.warehouse_id" placeholder="请选择" :options="form.country === 'US' ? options.destination_warehouse : options.plan_destination_warehouse" filterable
            clearable class="w-32" />
        </el-form-item>
        <el-form-item label="运输方式">
          <VSelect v-model="form.transport_type" placeholder="请选择" :options="options.transport_type" select filterable
            clearable class="w-32" />
        </el-form-item>
        <el-form-item label="需求数量">
          <el-input-number v-model="form.demand_num" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </el-form-item>
        <el-form-item label="需求到货日期">
          <el-date-picker v-model="form.demand_delivery_time" placeholder="日期选择" type="date"
            :disabled-date="val => val.getTime() < Date.now()" value-format="YYYY-MM-DD" class="w-32" />
        </el-form-item>
        <!-- <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="备注" type="textarea" :autosize="{ minRows: 1, maxRows: 1 }" />
        </el-form-item> -->
        <el-button type="primary" class="mb-[18px]" @click="update">修改</el-button>
      </div>
    </el-form>
    <el-form ref="formRef" :model="data">
      <vxe-table ref="tableRef" :data="data" :max-height="520">
        <vxe-column type="checkbox" width="40"></vxe-column>
        <vxe-column field="sku" title="sku" width="100" />
        <vxe-column field="sku_cn_title" title="产品名称" min-width="120">
          <template #default="{ row }">
            <VText :value="row.sku_cn_title" line="2" />
          </template>
        </vxe-column>
        <vxe-column title="* 活动类型" width="160">
          <template #header>
            <span class="text-red-600">*</span> 活动类型
          </template>
          <template #default="{ row, rowIndex }">
            <el-form-item :prop="[rowIndex, 'promotion_config_id']"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="row.promotion_config_id" placeholder="请选择" :options="options.typeOptions" select
                filterable clearable class="w-full" />
            </el-form-item>
          </template>
        </vxe-column>
        <vxe-column title="* 国家" width="160">
          <template #header>
            <span class="text-red-600">*</span> 国家
          </template>
          <template #default="{ row, rowIndex }">
            <el-form-item :prop="[rowIndex, 'country']" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="row.country" placeholder="请选择" :options="options.country" select filterable clearable
                class="w-full" @change="row.warehouse_id = ''"  />
            </el-form-item>
          </template>
        </vxe-column>
        <vxe-column title="* 仓库" width="160">
          <template #header>
            <span class="text-red-600">*</span> 仓库
          </template>
          <template #default="{ row, rowIndex }">
            <el-form-item :prop="[rowIndex, 'warehouse_id']"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="row.warehouse_id" placeholder="请选择" :options="row.country === 'US' ? options.destination_warehouse : options.plan_destination_warehouse" filterable
                clearable class="w-full" />
            </el-form-item>
          </template>
        </vxe-column>
        <vxe-column title="* 运输方式" width="120">
          <template #header>
            <span class="text-red-600">*</span> 运输方式
          </template>
          <template #default="{ row, rowIndex }">
            <el-form-item :prop="[rowIndex, 'transport_type']"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="row.transport_type" placeholder="请选择" :options="options.transport_type" select filterable
                clearable class="w-full" />
            </el-form-item>
          </template>
        </vxe-column>
        <vxe-column title="* 需求数量" width="100">
          <template #header>
            <span class="text-red-600">*</span> 需求数量
          </template>
          <template #default="{ row, rowIndex }">
            <el-form-item :prop="[rowIndex, 'demand_num']"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <el-input-number v-model="row.demand_num" :controls="false" :min="0" :step="1" :precision="0"
                class="w-full" />
            </el-form-item>
          </template>
        </vxe-column>
        <vxe-column title="* 需求到货日期" width="160">
          <template #header>
            <span class="text-red-600">*</span> 需求到货日期
          </template>
          <template #default="{ row, rowIndex }">
            <el-form-item :prop="[rowIndex, 'demand_delivery_time']"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <el-date-picker v-model="row.demand_delivery_time" placeholder="日期选择" type="date"
                :disabled-date="val => val.getTime() < Date.now()" value-format="YYYY-MM-DD" class="w-full" />
            </el-form-item>
          </template>
        </vxe-column>
        <vxe-column title="备注" width="120">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="备注" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
          </template>
        </vxe-column>
      </vxe-table>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
    <Goods ref="goodsRef" @change="goodsChange" />
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import Goods from '@/components/Goods'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const data = ref([])
const form = ref({})

const emit = defineEmits(['close', 'success'])

const goodsRef = ref()
const add = () => {
  goodsRef?.value.open()
}

const tableRef = ref()
const goodsChange = (val) => {
  const checkeds = val.filter(d => !data.value.some(s => s.p_id === d.p_id)).map(d => {
    return { p_id: d.p_id, sku: d.sku, sku_cn_title: d.sku_cn_title }
  })
  data.value.unshift(...checkeds)
}

const batchRemove = () => {
  const selection = tableRef?.value.getCheckboxRecords()
  data.value = data.value.filter(d => !selection.some(s => s.p_id === d.p_id))
}

const update = () => {
  const selection = tableRef?.value.getCheckboxRecords()
  if(!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  selection.forEach(d => {
    for (const key in form.value) {
      const value = form.value[key]
      if(value) {
        d[key] = value
      }
    }
  })
}

// 打开弹窗
const open = async () => {
  if (!load.value) {
    load.value = true
    await 1
  }
  data.value = []
  form.value = {}
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const formRef = ref()
const submit = async () => {
  if (!await formRef?.value?.validate()) return
  const data = tableRef?.value.getCheckboxRecords()
  if(!data.length) {
    ElMessage.warning('请先选择行')
    return
  }
  loadings.submit = true
  api.create({ data }).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>